import axios from 'axios'
import QueryString from 'qs';

function checkHttpStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const error = new Error(response.statusText);
  error.response = response;
  error.code = response.status;
  throw error;
}

function getResult(json) {
  if (json.status === 200) {
    let result = { data: json.data };
    return result;
  }
}
/**
 * 通用配置
 * @param url：接口地址
 * @param options：配置
 * @param return{*}
 */
function request(url = '', options = {}, cache) {
  let data;
  let contentType;
  if (typeof cache === 'function') {
    data = cache();
    if (data) {
      return Promise.resolve(data);
    }
  }
  data = options.data;
  delete options.data;
  contentType = options.contentType;
  delete options.contentType;
  const opts = {
    method: 'POST',
    url,
    ...options
  };
  opts.headers = {
    ...opts.headers,
  };
  if (opts.method === 'GET') {
    url = url.split('?');
    url = url[0] + '?' + QueryString.stringify(url[1] ? { ...QueryString.parse(url[1]), ...data } : data);
    opts.headers['content-type'] = contentType ? contentType : 'application/json'; //
  } else {
    opts.headers['content-type'] = contentType ? contentType : 'application/json'; //
    opts.data= contentType === 'application/x-www-form-urlencoded' ? serialize(data) : JSON.stringify(data);
  }
  // 支持处理缓存
  const handleCache = data => {
    typeof cache === 'function' && cache(data.result);
    return data;
  };

  return axios(opts)
    .then(checkHttpStatus)
    .then(getResult)
    .then(handleCache)
    .catch(err => ({ err }));
}
export default request;
